<template>
  <div class="mod-blog__art-manager">
    <SearchField :form="searchForm" @search="handleSearch">
      <el-form-item label="文章标题">
        <el-input v-model="searchForm.title" placeholder="请输入文章标题"></el-input>
      </el-form-item>
      <el-form-item label="文章作者">
        <el-input v-model="searchForm.author" placeholder="请输入文章作者"></el-input>
      </el-form-item>
      <el-form-item label="文章分类">
        <el-select v-model="searchForm.categoryId" placeholder="请选择文章分类" style="width: 180px;" clearable>
          <el-option v-for="item in categoryList" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
    </SearchField>
    <el-form :inline="true" :model="state.dataForm" @keyup.enter="state.getDataList()">
      <el-form-item>
        <el-button v-if="state.hasPermission('sys:params:save')" type="primary"
          @click="addOrUpdateHandle()">新增</el-button>
      </el-form-item>
    </el-form>
    <TableField :config="config" ref="tableRef">
      <el-table-column type="selection" width="55" fixed="left" align="center">
      </el-table-column>
      <el-table-column label="封面" prop="cover">
        <template #default="scope">
          <img v-if="scope.row.cover" class="acticleCover" :src="baseImgUrl + scope.row.cover" alt="">
          <div v-else>--</div>
        </template>
      </el-table-column>
      <el-table-column label="标题" prop="title" min-width="200px"></el-table-column>
      <el-table-column label="描述" prop="description" min-width="120px">
        <template #default="scope">
          <PopoverField :value="scope.row.description" popMaxWidth="500px" />
        </template>
      </el-table-column>
      <el-table-column label="作者" prop="author"></el-table-column>
      <el-table-column label="浏览量" prop="browseNum"></el-table-column>
      <el-table-column label="排序" prop="sort" align="center"></el-table-column>
      <el-table-column label="创建时间" prop="createDate" min-width="180px" align="center"></el-table-column>
      <el-table-column label="更新时间" prop="updateDate" min-width="180px" align="center"></el-table-column>
      <el-table-column label="操作" fixed="right" header-align="center" align="center" width="170">
        <template #default="scope">
          <el-button type="primary" link @click="addOrUpdateHandle(scope.row)">修改</el-button>
          <el-button type="primary" link @click="deleteItem(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </TableField>
    <ChyDrawer v-model="isShowDrawer" :title="dataForm.drawerTitle" @confirm="dataFormSubmitHandle()">
      <el-form :model="dataForm" class="data_form" ref="dataFormRef" :rules="rules"
        @keyup.enter="dataFormSubmitHandle()" label-width="auto" style="max-width: 600px">
        <el-form-item label="封面" prop="cover">
          <UploadField v-model="dataForm.cover" />
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="dataForm.title" />
        </el-form-item>
        <el-form-item label="标签" prop="tagIds">
          <el-select v-model="dataForm.tagIdList" multiple placeholder="请选择文章标签" clearable>
            <el-option v-for="item in tagList" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="dataForm.categoryId" placeholder="请选择文章分类" clearable>
            <el-option v-for="item in categoryList" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="dataForm.description" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <EditorField v-model="dataForm.content" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="dataForm.sort" :min="1" :max="999" />
        </el-form-item>
      </el-form>
    </ChyDrawer>
  </div>
</template>

<script setup lang='ts'>
import useView from '@/hooks/useView'
import { ref, reactive, toRefs, onMounted } from 'vue'
import TableField from '@/components/table-field'
import UploadField from '@/components/upload-field'
import PopoverField from '@/components/popover-field'
import ChyDrawer from "@/components/chy-drawer"
import EditorField from "@/components/editor-field/index.vue"
import SearchField from '@/components/search-field'
import http from "@/utils/http"
import { ElMessage } from "element-plus"
import { addBlogArticle, updateBlogArticle } from "@/api/blogArticle"
import { getBlogTag } from '@/api/blogTag'
import { getBlogCategory } from "@/api/blogCategory"

const view = reactive({
  deleteURL: "blogArticle"
})
const state = reactive({ ...useView(view), ...toRefs(view) })

const baseImgUrl = import.meta.env.VITE_APP_DOWNLOAD_IMG_API

let config = ref({
  url: 'blogArticle',
  rootProperty: 'list',
  method: 'get',
  data: {
    // order: 'desc',
    // orderField: 'sort'
  }
})

const tableRef = ref()

const searchForm = ref({
  title: '',
  author: '',
  categoryId: undefined
})

const dataFormRef = ref()

const isShowDrawer = ref(false)

type CategoryType = {
  id: number,
  name: string,
  sort: number
}
let categoryList = ref<Array<CategoryType>>([])
getBlogCategory().then(res => {
  categoryList.value = res.data
})
interface ITag {
  id: string,
  name: string,
}

let tagList = ref<Array<ITag>>([])
getBlogTag().then((res: any) => {
  tagList.value = res.data.list
})


type DataType = {
  id?: number,
  cover: string,
  drawerTitle: string,
  title: string,
  tagIdList: Array<string>,
  tagIds: string,
  categoryId?: string,
  description: string,
  name: string,
  sort: number,
  content: string
}
const dataForm = reactive<DataType>({
  id: undefined,
  cover: '',
  drawerTitle: '',
  title: '',
  tagIdList: [],
  tagIds: '',
  categoryId: '0',
  description: '',
  name: '',
  content: '',
  sort: 0,
})

const rules = ref({
  cover: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  title: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  sort: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
})

onMounted(() => {
  tableRef.value.loadData()
})

const handleSearch = (searchParams: any) => {
  config.value.data = { ...config.value.data, ...searchParams }
  tableRef.value.loadData()
}

const addOrUpdateHandle = (row?: any) => {
  isShowDrawer.value = true
  dataFormReset()
  if (!row) {
    dataForm.drawerTitle = '新增'
  } else {
    dataForm.drawerTitle = '修改'
    dataForm.id = row.id
    dataForm.categoryId = row.categoryId
    dataForm.tagIds = row.tagIds
    dataForm.tagIdList = dataForm.tagIds?.split(',');
    dataForm.cover = row.cover
    dataForm.title = row.title
    dataForm.content = row.content
    dataForm.sort = row.sort
  }
}

const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false
    }
    dataForm.tagIds = dataForm.tagIdList.join(',');
    (!dataForm.id ? addBlogArticle : updateBlogArticle)({ ...dataForm }).then(res => {
      if (res.code === 0) {
        ElMessage.success({
          message: "成功",
          duration: 500,
          onClose: () => {
            isShowDrawer.value = false
            tableRef.value.loadData()
          }
        })
      }
    })
  })

}

const dataFormReset = () => {
  dataForm.id = undefined
  dataForm.cover = ''
  dataForm.title = ''
  dataForm.tagIds = ''
  dataForm.tagIdList = []
  dataForm.sort = 0
  dataForm.content = '<p><br></p>'
  dataForm.cover = ''
}

const deleteItem = (id: string) => {
  state.deleteHandle(id).then(res => {
    if (res) {
      tableRef.value.loadData()
    }
  })
}

</script>

<style lang='scss' scoped>
.acticleCover {
  width: 100px;
  height: 50px;
}

.editor {
  height: 400px;
}
</style>